package com.agilespirit.presentation.pages.application.wizard;


import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import com.agilespirit.application.ApplicationServiceImpl;
import com.agilespirit.domain.Application;
import com.agilespirit.presentation.components.application.wizard.ApplicationCreationWizard;
import com.agilespirit.presentation.components.application.wizard.ApplicationEditionWizard;
import com.agilespirit.presentation.components.application.wizard.ApplicationWizard;

public class ApplicationWizardPage extends WebPage {

  /* Components */
  ApplicationWizard applicationWizard;

  /* Models */
  IModel<Application> applicationModel;
  boolean edition;

  public ApplicationWizardPage() {
    buildApplicationCreationWizard();
  }

  public ApplicationWizardPage(PageParameters params) {
    Integer applicationId = Integer.parseInt(params.get("application").toString());
    if (ApplicationServiceImpl.getInstance().getById(applicationId) != null) {
      buildApplicationEditionWizard(applicationId);
    } else {
      buildApplicationCreationWizard();
    }
  }

  private void buildApplicationCreationWizard() {
    applicationModel = new CompoundPropertyModel<Application>(new LoadableDetachableModel<Application>() {
      @Override
      protected Application load() {
        Application application = Application.create();
        return application;
      }
    });
    edition = false;
    add(new ApplicationCreationWizard("applicationWizard", applicationModel));
  }

  private void buildApplicationEditionWizard(final Integer applicationId) {
    applicationModel = new CompoundPropertyModel<Application>(new LoadableDetachableModel<Application>() {
      @Override
      protected Application load() {
        Application application = ApplicationServiceImpl.getInstance().getById(applicationId);
        return application;
      }
    });
    edition = true;
    add(new ApplicationEditionWizard("applicationWizard", applicationModel));
  }

}
